﻿using System;
using System.ServiceModel.Description;
using Microsoft.Practices.Unity;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;

namespace WDA.Core
{
	/// <summary>
	/// Customizes WCF instance creation process forcing it to resolve contract implementations using 
	/// particular Unity container instance.	
	/// </summary>
	internal class ManagedEndpointBehavior : IEndpointBehavior
	{
      private readonly string _serviceName;

		/// <summary>
		/// Main general-purpose runtime-level container.
		/// </summary>
		[Dependency]
		public IUnityContainer Container { get; set; }

		/// <summary>
		/// TCreates new behavior instance.
		/// </summary>
		/// <param name="serviceName">Name of WDAB servie published using this endpoint.</param>
		public ManagedEndpointBehavior(string serviceName)
		{
         _serviceName = serviceName;
		}

		#region IEndpointBehavior Members
		public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
		{
		}
		public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
		{
		}
		public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
		{
			Type contractType = endpoint.Contract.ContractType;
			ManagedInstanceProvider instanceProvider = new ManagedInstanceProvider(contractType, _serviceName);
			endpointDispatcher.DispatchRuntime.InstanceProvider = Container.BuildUp(instanceProvider);         
		}
		public void Validate(ServiceEndpoint endpoint)
		{
		}
		#endregion
	}	
}
